package com.mmall.common;

import com.mmall.util.PropertyUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by root on 18-5-10.
 */
public class RedisPool {

    private static JedisPool jedisPool;
    private static Integer maxTotal = Integer.parseInt(PropertyUtil.getProperty("redis.max.total", "20"));
    private static Integer maxIdle = Integer.parseInt(PropertyUtil.getProperty("redis.max.idle", "10"));
    private static Integer minIde = Integer.parseInt(PropertyUtil.getProperty("redis.min.idle", "2"));
    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertyUtil.getProperty("redis.test.onBorrow", "true"));
    private static Boolean testOnReTurn = Boolean.parseBoolean(PropertyUtil.getProperty("redis.test.onReturn", "false"));
    private static String  redisIp = PropertyUtil.getProperty("redis.ip");
    private static Integer redisPort = Integer.parseInt(PropertyUtil.getProperty("redis.port", "6379"));
    private static Integer timeout = Integer.parseInt(PropertyUtil.getProperty("redis.timeout", "2")); //unit:second

    static {
        initPool();
    }

    private static void initPool () {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(maxIdle);
        poolConfig.setMaxTotal(maxTotal);
        poolConfig.setMinIdle(minIde);
        poolConfig.setTestOnBorrow(testOnBorrow);
        poolConfig.setTestOnReturn(testOnReTurn);
        poolConfig.setBlockWhenExhausted(true);
        jedisPool = new JedisPool(poolConfig, redisIp, redisPort, timeout * 1000);
    }

    public static Jedis getResource(){
        return jedisPool.getResource();
    }

    public static void returnResource(Jedis jedis) {
        jedisPool.returnResource(jedis);
    }

    public static void returnBrokenResource(Jedis jedis) {
        jedisPool.returnBrokenResource(jedis);
    }

    public static void main(String[] args) {
        Jedis jedis = getResource();
        jedis.set("testkey", "testvalue");
        returnResource(jedis);
        System.out.println("test end");
    }

}
